import reactive from './reactive'
import { createPool } from './pool'
import { bindEvent } from './event'
import { render } from './render'

export function createApp(component) {
  const vm = {}

  const $data = component.data
  const $methods = component.methods
  const $template = component.template

  vm.DOM = createDOM($template)
  const { propsPool, eventPool } = createPool(vm.DOM, $methods)

  console.log(propsPool, eventPool)

  vm.mount = mount

  const init = function () {
    reactive(vm, $data, propsPool)
    bindEvent(vm, eventPool)
    render(vm, propsPool)
  }

  init()

  return vm
}

function createDOM(template) {
  const _dom = document.createElement('div')
  _dom.innerHTML = template
  return getFirstElementChild(_dom)
}

function getFirstElementChild(node) {
  const childNodes = node.childNodes
  let childNode

  for (let i = 0; i < childNodes.length; i++) {
    childNode = childNodes[i]

    // 元素节点
    if (childNode.nodeType === 1) {
      return childNode
    }
  }
}

function mount(el) {
  console.log(el, document.querySelector(el), this)
  document.querySelector(el).appendChild(this.DOM)
  return this
}